//
//  FTGuideScrollController.m
//  FTGuideScrollController
//
//  Created by JackieYip on 2017/6/7.
//  Copyright © 2017年 mondial-d. All rights reserved.
//

#import "FTGuideScrollController.h"
#import "UIImageView+FTCache.h"
#import "UIImageView+FTLanguage.h"
#import "NSString+Verifying.h"
#import "NSString+Custom.h"
#import "FTImage.h"
#import "FTMacro_Screen.h"
#import "FTMacro_Font.h"
#import "FTDebug_Macro.h"

@interface FTGuideScrollController ()
@property (assign, nonatomic, readwrite) FTGuideContentDirection contentDirection;
@property (strong, nonatomic, readwrite) UIColor *backgroundColor;
@property (assign, nonatomic, readwrite) CGFloat alpha;
@property (strong, nonatomic, readwrite) UIScrollView *scrollView;
// id : FTImage 或 NSString
@property (strong, nonatomic, readwrite) NSArray <id>*images;
@property (strong, nonatomic, readwrite) UIButton *prePageButton;
@property (strong, nonatomic, readwrite) UIButton *nextPageButton;
// bottomButtonImage = @[@"buttonImageNameString", @"buttonTitle"]
@property (strong, nonatomic, readwrite) NSArray <NSString *>*bottomButtonImage;
@property (strong, nonatomic, readwrite) void (^didLoadImageOnResponse)();
@property (strong, nonatomic, readwrite) void (^shutDownOnResponse)();
@property (strong, nonatomic, readwrite) void (^clicksOnBottomButton)();
@property (assign, nonatomic, readwrite) BOOL timeout;
@property (assign, nonatomic, readwrite) BOOL needDetectedTimeout;@end

@implementation FTGuideScrollController

- (instancetype)initWithGuideImages:(NSArray <id>*)images contentDirection:(FTGuideContentDirection)contentDirection backgroundColor:(UIColor *)backgroundColor alpha:(CGFloat)alpha didLoadImageOnResponse:(void (^)())didLoadImageOnResponse shutDownOnResponse:(void(^)())shutDownOnResponse
{
    return [self initWithGuideLocalImages:images contentDirection:contentDirection backgroundColor:backgroundColor alpha:alpha bottomButtonImage:nil didLoadImageOnResponse:didLoadImageOnResponse shutDownOnResponse:shutDownOnResponse clicksOnBottomButton:nil];
}

- (instancetype)initWithGuideLocalImages:(NSArray <id>*)images contentDirection:(FTGuideContentDirection)contentDirection backgroundColor:(UIColor *)backgroundColor alpha:(CGFloat)alpha bottomButtonImage:(NSArray <NSString *>*)bottomButtonImage didLoadImageOnResponse:(void (^)())didLoadImageOnResponse shutDownOnResponse:(void(^)())shutDownOnResponse clicksOnBottomButton:(void (^)())clicksOnBottomButton
{
    if (self = [super init]) {
        self.images = images;
        self.contentDirection = contentDirection;
        self.backgroundColor = backgroundColor;
        self.alpha = alpha;
        self.bottomButtonImage = bottomButtonImage;
        self.didLoadImageOnResponse = didLoadImageOnResponse;
        self.shutDownOnResponse = shutDownOnResponse;
        self.clicksOnBottomButton = clicksOnBottomButton;
        // 转场
        [[UIApplication sharedApplication].keyWindow addSubview:self.view];
        CGAffineTransform transform = CGAffineTransformMakeScale(0.7, 0.7);
        self.view.transform = transform;
        
        if (![backgroundColor isEqual:[UIColor clearColor]])
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        [UIView animateWithDuration:0.1 animations:^{
            CGAffineTransform scale = CGAffineTransformMakeScale(1.05, 1.05);
            self.view.transform = scale;
        } completion:^(BOOL finished) {
            if (![backgroundColor isEqual:[UIColor clearColor]])
                [UIApplication sharedApplication].statusBarHidden = YES;
            [UIView animateWithDuration:0.1 animations:^{
                CGAffineTransform scale = CGAffineTransformMakeScale(1, 1);
                self.view.transform = scale;
            }];
        }];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI
{
    // self view
    self.view.backgroundColor = self.backgroundColor;
    self.view.alpha = self.alpha;
    UIImage *shutDownImage = nil;
    // mark view
    if ([self.backgroundColor isEqual:[UIColor clearColor]]) {
        UIView *markView = [[UIView alloc] initWithFrame:self.view.bounds];
        markView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        [self.view addSubview:markView];
        shutDownImage = [UIImage imageNamed:@"icon-cancel-white"];
    }
    else if ([self.backgroundColor isEqual:[UIColor blackColor]])
        shutDownImage = [UIImage imageNamed:@"icon-cancel-white"];
    else
        shutDownImage = [UIImage imageNamed:@"icon-cancel"];
    
    // scroll view
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView = scrollView;
    self.scrollView.delegate = (id)self;
    [self.view addSubview:scrollView];
    
    // scroll view content
    // 用于垂直scroll view
    __block CGFloat preImageViewMaxY = 0;
    // 用于水平scroll view
    __block CGFloat preImageViewMaxX = 0;
    [self.images enumerateObjectsUsingBlock:^(id _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([image isKindOfClass:[FTImage class]]) {
            FTImage *ftImage = image;
            if ([image isValidImage]) {
                CGRect rect = CGRectZero;
                // 垂直
                if (self.contentDirection == FTGuideContentDirection_vertical) {
                    CGFloat height = ftImage.height/ftImage.width * kScreenWidth;
                    rect = CGRectMake(0, preImageViewMaxY, kScreenWidth, height);
                    preImageViewMaxY += height;
                }
                // 水平
                else if (self.contentDirection == FTGuideContentDirection_horizontal) {
                    CGFloat height = ftImage.height/ftImage.width * kScreenWidth;
                    CGFloat y = (kScreenHeight - height)/2;
                    rect = CGRectMake(preImageViewMaxX, y, kScreenWidth, height);
                    preImageViewMaxX += kScreenWidth;
                }
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
                imageView.backgroundColor = [UIColor clearColor];
                [imageView ft_setImageWithURL:ftImage.URL placeholderImage:nil];
                
                // 超时检测
                self.needDetectedTimeout = YES;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Float64)5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                    if (self.needDetectedTimeout)
                        self.timeout = YES;
                });
                self.timeout = NO;
                while (![NSStringFromCGSize(imageView.image.size) isEqualToString:NSStringFromCGSize(CGSizeZero)]) {
                    if (self.timeout) {
                        FTLog(@"图片还没有加载下来，超时啦");
                        break;
                    }
                }
                self.needDetectedTimeout = NO;
                
                [self.scrollView addSubview:imageView];
            }
        }
        else if ([image isKindOfClass:[NSString class]]) {
            NSString *imageString = image;
            CGRect rect = CGRectZero;
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
            imageView.backgroundColor = [UIColor clearColor];
            imageView.pngImageLocalString = imageString;
            
            // 垂直
            if (self.contentDirection == FTGuideContentDirection_vertical) {
                CGFloat height = imageView.image.size.height;
                rect = CGRectMake(0, preImageViewMaxY, kScreenWidth, height);
                preImageViewMaxY += height;
            }
            // 水平
            else if (self.contentDirection == FTGuideContentDirection_horizontal) {
                CGFloat height = imageView.image.size.height;
                CGFloat y = (kScreenHeight - height)/2;
                rect = CGRectMake(preImageViewMaxX, y, kScreenWidth, height);
                preImageViewMaxX += kScreenWidth;
            }
            
            [self.scrollView addSubview:imageView];
        }
    }];
    // shut down button
    UIButton *shutDownButton = [UIButton buttonWithType:UIButtonTypeCustom];
    // 垂直
    if (self.contentDirection == FTGuideContentDirection_vertical) {
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.contentSize = CGSizeMake(0, preImageViewMaxY);
        if (self.bottomButtonImage.count > 0) {
            __block UIButton *button = nil;
            __block CGSize titleSize = CGSizeZero;
            [self.bottomButtonImage enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (!button) {
                    button = [UIButton buttonWithType:UIButtonTypeCustom];
                    [button setImage:[UIImage imageNamed:obj] forState:UIControlStateNormal];
                    [button addTarget:self action:@selector(clicksOnBottomButtonAndShutDown) forControlEvents:UIControlEventTouchUpInside];
                    button.layer.cornerRadius = 3.0;
                    button.layer.borderColor = [UIColor whiteColor].CGColor;
                    button.layer.borderWidth = 1/[UIScreen mainScreen].scale;
                }
                else if (idx == 1) {
                    [button setTitle:obj forState:UIControlStateNormal];
                    button.titleLabel.font = kFont18;
                    [button.titleLabel sizeToFit];
                    titleSize = [obj calculateSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) font:kFont18];
                }
            }];
            if (button) {
                CGFloat width = button.imageView.image.size.width + titleSize.width + 50;
                CGFloat height = button.imageView.image.size.height > titleSize.height ? button.imageView.image.size.height : titleSize.height;
                height = height > 0 ? height + 20 : 0;
                button.frame = CGRectMake((kScreenWidth - width)/2, self.scrollView.contentSize.height - height - 80, width, height);
                [self.scrollView addSubview:button];
                
                shutDownButton.frame = CGRectMake((kScreenWidth - 44)/2, CGRectGetMaxY(button.frame) + 10, 44, 44);
                [self.scrollView addSubview:shutDownButton];
            }
        }
    }
    // 水平
    else if (self.contentDirection == FTGuideContentDirection_horizontal) {
        self.scrollView.contentSize = CGSizeMake(preImageViewMaxX, 0);
        self.scrollView.pagingEnabled = YES;
        CGFloat buttonWidth = 44;
        CGFloat buttonHeight = 44;
        
        // pre page button
        UIButton *prePageButton = [UIButton buttonWithType:UIButtonTypeCustom];
        prePageButton.frame = CGRectMake(0, self.view.center.y - buttonHeight/2, buttonWidth, buttonHeight);
        [prePageButton setImage:[UIImage imageNamed:@"arrow-left"] forState:UIControlStateNormal];
        [prePageButton addTarget:self action:@selector(prePage) forControlEvents:UIControlEventTouchUpInside];
        prePageButton.hidden = YES;
        self.prePageButton = prePageButton;
        [self.view addSubview:prePageButton];
        
        // next page button
        UIButton *nextPageButton = [UIButton buttonWithType:UIButtonTypeCustom];
        nextPageButton.frame = CGRectMake(kScreenWidth - buttonWidth, self.view.center.y - buttonHeight/2, buttonWidth, buttonHeight);
        [nextPageButton setImage:[UIImage imageNamed:@"arrow-right"] forState:UIControlStateNormal];
        [nextPageButton addTarget:self action:@selector(nextPage) forControlEvents:UIControlEventTouchUpInside];
        if (self.images.count <= 1)
            nextPageButton.hidden = YES;
        self.nextPageButton = nextPageButton;
        [self.view addSubview:nextPageButton];
    }
    
    [shutDownButton setImage:shutDownImage forState:UIControlStateNormal];
    [shutDownButton addTarget:self action:@selector(shutDown) forControlEvents:UIControlEventTouchUpInside];
    if (!shutDownButton.superview) {
        shutDownButton.frame = CGRectMake(kScreenWidth - 44 - 20, 30, 44, 44);
        [self.view addSubview:shutDownButton];
    }
    
    if (self.didLoadImageOnResponse)
        _didLoadImageOnResponse();
}

- (void)prePage
{
    // 滚上一页
    CGPoint offset = self.scrollView.contentOffset;
    offset.x -= kScreenWidth;
    [self.scrollView setContentOffset:offset animated:YES];
}

- (void)nextPage
{
    // 滚下一页
    CGPoint offset = self.scrollView.contentOffset;
    offset.x += kScreenWidth;
    [self.scrollView setContentOffset:offset animated:YES];
}

- (void)shutDown
{
    if (_shutDownOnResponse) {
        if (![self.backgroundColor isEqual:[UIColor clearColor]]) {
            [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
            [UIApplication sharedApplication].statusBarHidden = NO;
        }
        [self.view removeFromSuperview];
        _shutDownOnResponse();
    }
    else
        [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)clicksOnBottomButtonAndShutDown
{
    if (_clicksOnBottomButton) {
        _clicksOnBottomButton();
    }
}

- (void)removeSelfViewFromSuperView
{
    [self.view removeFromSuperview];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.contentDirection == FTGuideContentDirection_horizontal)
    {
        if (self.scrollView.contentOffset.x <= kScreenWidth/2)
            self.prePageButton.hidden = YES;
        else
            self.prePageButton.hidden = NO;
        if (self.scrollView.contentOffset.x >= ((self.images.count - 2) * kScreenWidth) + kScreenWidth/2)
            self.nextPageButton.hidden = YES;
        else
            self.nextPageButton.hidden = NO;
    }
}

@end
